package com.intelligence.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligence.common.system.AuthContextUtil;
import com.intelligence.common.system.MenuHelper;
import com.intelligence.entity.pojo.SysUser;
import com.intelligence.entity.result.Result;
import com.intelligence.entity.result.ResultCodeEnum;
import com.intelligence.entity.vo.SysMenuVo;
import com.intelligence.mapper.SysPermissionMapper;
import com.intelligence.entity.pojo.SysPermission;
import com.intelligence.mapper.SysRolePermissionMapper;
import com.intelligence.service.SysPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
* @author Administrator
* @description 针对表【sys_permission】的数据库操作Service实现
* @createDate 2024-05-15 19:38:31
*/
@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission>
    implements SysPermissionService {
    @Autowired
    private SysPermissionMapper sysPermissionMapper;
    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;
    @Override
    public Result<List<SysMenuVo>> findNodes() {
        SysUser sysUser = AuthContextUtil.get();
        List<SysPermission> sysPermissions = MenuHelper.buildTree(sysPermissionMapper.findNodesByUserId(sysUser.getId()));
        List<SysMenuVo> sysMenuVos = this.buildMenus(sysPermissions);
        return Result.build(sysMenuVos, ResultCodeEnum.SUCCESS);
    }

    @Override
    public Map<String, Object> findSysRoleMenuByRoleId(Long roleId) {
        // 查询所有的菜单数据
        List<SysPermission> sysPermissions = sysPermissionMapper.selectList(null);
        List<SysPermission> sysPermissions1 = MenuHelper.buildTree(sysPermissions);
        // 查询当前角色的菜单数据
        List<Long> roleMenuIds= sysPermissionMapper.findNodesIdByRoleId(roleId);
        // 将数据存储到Map中进行返回
        Map<String , Object> result = new HashMap<>();
        result.put("sysMenuList" , sysPermissions1);
        result.put("roleMenuIds" , roleMenuIds);
        // 返回
        return result;
    }

    // 将List<SysMenu>对象转换成List<SysMenuVo>对象
    private List<SysMenuVo> buildMenus(List<SysPermission> sysPermissionList) {

        List<SysMenuVo> sysMenuVoList = new LinkedList<SysMenuVo>();
        for (SysPermission sysMenu : sysPermissionList) {
            SysMenuVo sysMenuVo = new SysMenuVo();
            sysMenuVo.setTitle(sysMenu.getName());
            sysMenuVo.setName(sysMenu.getCss());
            List<SysPermission> children = sysMenu.getChildren();
            if (!CollectionUtils.isEmpty(children)) {
                sysMenuVo.setChildren(buildMenus(children));
            }
            sysMenuVoList.add(sysMenuVo);
        }
        return sysMenuVoList;
    }

}




